package unv.esiag.uchiha.subscribers.impl;

import java.io.Serializable;
import java.rmi.RemoteException;
import java.util.Vector;

import unv.esiag.uchiha.core.Agent;
import unv.esiag.uchiha.readers.DataReactor;
import unv.esiag.uchiha.semaphore.Semaphore;
import unv.esiag.uchiha.subscribers.Subscriber;

public class SubscriberImpl implements Subscriber{
	private Vector<DataReactor> listeners;
	private static final int MAXLEN = 5;
	private static Vector<SubscriberImpl> subscribers;
	private Semaphore listenerS;
	private String ior;
	private SubscriberImpl() {
		this.listeners = new Vector<DataReactor>();
		ior = Agent.getInstance().subscriber_to_ior(this);
		this.listenerS = new Semaphore();
	}
	public String getIor() {
		return ior;
	}
	public void addDataListener(DataReactor listener){
		this.listenerS.stop();
		this.listeners.add(listener);
		this.listenerS.signal();
	}
	
	public int getListenersCount(){
		return this.listeners.size();
	}
	
	synchronized public void publish(Serializable serializable) throws RemoteException {
		this.listenerS.stop();
		for(int i = 0;i<this.listeners.size();i++){
			this.listeners.get(i).addOperation(serializable);
		}
		this.listenerS.signal();
	}
	synchronized public static SubscriberImpl getSubscriber(DataReactor listener){
		SubscriberImpl subs = null;
		if(subscribers == null){
			subscribers = new Vector<SubscriberImpl>();
			subs = new SubscriberImpl();
			subscribers.add(subs);
		}else{
			subs = subscribers.get(subscribers.size() - 1);
			if(subs.getListenersCount() == MAXLEN){
				subs = new SubscriberImpl();
				subscribers.add(subs);
			}
		}
		subs.addDataListener(listener);
		return subs;
	}
}
